package danran.bfs;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

/**
 * @Classname coinChange
 * @Description TODO
 * @Date 2021/8/28 14:40
 * @Created by ASUS
 */
public class coinChange {
    public static void main(String[] args) {
        System.out.println(new coinChange().coinChange(new int[]{1, 2, 5}, 11));
    }

    public int coinChange_dp(int[] coins, int amount) {
        int[][] dp = new int[coins.length + 1][amount + 1];
        for (int[] ints : dp) Arrays.fill(ints, Integer.MAX_VALUE);
        for (int i = 0; i < coins.length; i++) dp[i][0] = 0;
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                // 不取当前的硬币
                dp[i][j] = dp[i - 1][j];
                // 取当前硬币
                if (j >= coins[i - 1] && dp[i][j - coins[i - 1]] != Integer.MAX_VALUE) {
                    dp[i][j] = Math.min(dp[i][j], dp[i][j - coins[i - 1]] + 1);
                }
            }
        }
        return dp[coins.length][amount] == Integer.MAX_VALUE ? -1 : dp[coins.length][amount];
    }

    public int coinChange(int[] coins, int amount) {
        if (amount < 0) return -1;
        if (coins.length == 0) return -1;
        Queue<Integer> q = new ArrayDeque<>();
        Queue<Integer> remain = new ArrayDeque<>();
        for (int coin : coins) {
            q.offer(coin);
            remain.offer(amount);
        }
        int step = 0;
        while (!q.isEmpty()) {
            int size = q.size();
            step++;
            for (int i = 0; i < size; i++) {
                Integer cur = q.poll();
                Integer cur_remain = remain.poll();
                if (cur_remain - cur == 0) return step;
                for (int coin : coins) {
                    q.offer(coin);
                    remain.offer(cur_remain - cur);
                }
            }
        }
        return -1;
    }

    public int coinChangeII(int[] coins, int amount) {
        int[][] dp = new int[coins.length + 1][amount + 1];
        // base case:当前包包的容量为0时，可以采取的方法为1
        for (int i = 0; i < dp.length; i++) dp[i][0] = 1;
        for (int i = 1; i < dp.length; i++) {
            for (int j = 0; j < amount + 1; j++) {
                // 不取当前的硬币
                dp[i][j] = dp[i - 1][j];
                if (j >= coins[i - 1]) dp[i][j] += dp[i][j - coins[i - 1]];
            }
        }
        return dp[coins.length][amount];
    }


}
